package com.example.springboot.hl7;

import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HapiContext;
import ca.uhn.hl7v2.app.HL7Service;
import ca.uhn.hl7v2.llp.MinLowerLayerProtocol;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.util.Objects;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HL7ServiceUtils {

    private static final int PORT_NUMBER  = 9999;

    public static void startMLLPService(HL7ServiceInfo serviceInfo){
        Integer port = serviceInfo.getPort();
        if (Objects.isNull(port)){
            port = PORT_NUMBER;
        }
        serviceInfo.setPort(port);
        try (HapiContext context = new DefaultHapiContext()){
            ThreadPoolExecutor executor = new ThreadPoolExecutor(
                    8, 12,
                    30, TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(100));
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            MinLowerLayerProtocol mllp = new MinLowerLayerProtocol();
            mllp.setCharset("UTF-8");
            context.setLowerLayerProtocol(mllp);
            context.setExecutorService(executor);
            boolean useSecureConnection = false; // are you using TLS/SSL?
            HL7Service ourHl7Server = context.newServer(port, useSecureConnection);
            ourHl7Server.registerApplication(new HL7MessageReceivingApplication(serviceInfo));
            ourHl7Server.startAndWait();
            serviceInfo.setRun(true);
            serviceInfo.setHost(InetAddress.getLocalHost().getHostAddress());
            log.info("MLLP-HL7消息接收服务启动成功，info：{}",serviceInfo);
        } catch (Exception e) {
            e.printStackTrace();
            serviceInfo.setRun(false);
            serviceInfo.setRunMsg(e.getMessage());
        }
    }

}
